# -*- coding: utf-8 -*-
#
# Copyright 2009 Vanderbilt University
# 
# Licensed under the Apache License, Version 2.0 (the "License"); 
# you may not use this file except in compliance with the License. 
# You may obtain a copy of the License at 
# 
#     http://www.apache.org/licenses/LICENSE-2.0 
# 
# Unless required by applicable law or agreed to in writing, software 
# distributed under the License is distributed on an "AS IS" BASIS, 
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
# See the License for the specific language governing permissions and 
# limitations under the License. 

"""

.. moduleauthor:: John Paulett <john.paulett -at- vanderbilt.edu>
"""

from __future__ import division
from hornet.event import GraphsReady
from hornet.plugin import Plugin, log
from hornet.util import accumulate
import hornet.network
import hornet.plot as plot
import logging
import operator

logger = logging.getLogger(__name__)

def standardize(data):
    def func(x):
        key = max([k for k in data if k < x])
        return data[key]
    return func
    
class TransactionsThreshold(object):
    def value(self, edge):
        return edge[2].size
    
    def total(self, graph):
        return hornet.network.transaction_count(graph)
    
class EdgeThreshold(object):
    def value(self, edge):
        return 1
    
    def total(self, graph):
        return graph.size()
    
class ThresholdDetect(Plugin):
    """Compares the number of transactions disregarded as a threshold is increased.
    """
    def setup(self):
        self.scale = False
        self.results = {}
        logger.debug('ThresholdDetect plugin created')
 
    def teardown(self):
        del self.rules
        logger.debug('ThresholdDetect plugin destroyed')
    
    @log
    def notify(self, event):
        for graph  in event.data:
            pdf = {}
            for edge in graph.edges_iter(data=True):
                value = getattr(edge[2], self.measure)
                if value not in pdf:
                    pdf[value] = 0
                pdf[value] += self.thresholder.value(edge)

            if self.scale:
                total = self.thresholder.total(graph)
                for k, v in pdf.iteritems():
                    pdf[k] = v / total
            
            result = accumulate(pdf)
            self.results[graph.meta.period] = result    
            plot.xyscatter(result.keys(), result.values(), fmt='.')
            plot.show()
            #FIXME premature end
            break
    
    def accepted_events(self):
        return GraphsReady
    